<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Factory_m extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
	
	function saveorder()
	{
		
		$postdata="";
		$str="";
		$orderId = intval($this->input->post('orderId'));
		if(!$orderId)
		{
			 $this->fun->phpalert(2, "参数错误！");
              die;
		}
		$order = $this->fun->getdatabasesdetail("db_factory_order"," AND id='".$orderId."'");//订单详细
		$sell = $this->fun->getdatabasesdetail("db_factory_sell"," AND orderId='".$orderId."'");
		
		if($order['status'] == 3)	//如果当前订单为生产完成！只允许修改工人，裁剪，质检
		{
			$postdata["proWorker"] = $this->input->post('proWorker');
			if(($sell["proWorker"] != $this->input->post('proWorker') ) && $sell["proWorker"])
			{
				$userinfo = $this->fun->userinfo($this->input->post('proWorker'));
				$olduserinfo = $this->fun->userinfo($sell["proWorker"]);
				$str.= ";原生产工人:{$olduserinfo[name]} 被修改为：".$userinfo["name"];
			}
			
			$postdata["person1"] = $this->input->post('person1');
			if(($sell["person1"] != $this->input->post('person1')) && $sell["person1"])
			{
				$person1 = $this->fun->userinfo($this->input->post('person1'));
				$olduserinfo = $this->fun->userinfo($sell["person1"]);
				$str.= ";原裁剪:{$olduserinfo[name]} 被修改为：".$person1["name"];
			}
			
			$postdata["person3"] = $this->input->post('person3');
			if(($sell["person3"] != $this->input->post('person3')) && $sell["person3"])
			{
				$person3 = $this->fun->userinfo($this->input->post('person3'));
				$olduserinfo = $this->fun->userinfo($sell["person3"]);
				$str.= ";原质检:{$olduserinfo[name]} 被修改为：".$person3["name"];
			}
			$this->db->update("db_factory_sell",$postdata," orderId='".$orderId."'");
			if($str){
				 $this->db->insert("db_factory_orderlog",array("orderId"=>$orderId,"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>$str,"spcodeid"=>1));
			  }
			return $orderId;

		}



		$postdata["custom"] = $this->input->post('chima');
		if(($sell["custom"] != $this->input->post('chima') ) && $sell["custom"])
		{
			if( $this->input->post('chima')==1) $chima ="均码";
			if( $this->input->post('chima')==2) $chima ="定制";
			$str.= "尺寸选择:{$sell[custom]} 被修改为：{$chima}";
		}

		$postdata["price"] = $this->input->post('price');
		if($sell["price"] != $this->input->post('price'))
		{
			$str.= ";原工价:{$sell[price]} 被修改为：".$this->input->post('price');
		}
		
		$postdata["proWorker"] = $this->input->post('proWorker');
		if(($sell["proWorker"] != $this->input->post('proWorker') ) && $sell["proWorker"])
		{
			$userinfo = $this->fun->userinfo($this->input->post('proWorker'));
			$olduserinfo = $this->fun->userinfo($sell["proWorker"]);
			$str.= ";原生产工人:{$olduserinfo[name]} 被修改为：".$userinfo["name"];
		}
		$postdata["person1"] = $this->input->post('person1');
		if(($sell["person1"] != $this->input->post('person1')) && $sell["person1"])
		{
			$person1 = $this->fun->userinfo($this->input->post('person1'));
			$olduserinfo = $this->fun->userinfo($sell["person1"]);
			$str.= ";原裁剪:{$olduserinfo[name]} 被修改为：".$person1["name"];
		}
		
		$postdata["person3"] = $this->input->post('person3');
		if(($sell["person3"] != $this->input->post('person3')) && $sell["person3"])
		{
			$person3 = $this->fun->userinfo($this->input->post('person3'));
			$olduserinfo = $this->fun->userinfo($sell["person3"]);
			$str.= ";原质检:{$olduserinfo[name]} 被修改为：".$person3["name"];
		}

		$postdata["scale"] = $this->input->post('scale');
		if(($sell["scale"] != $this->input->post('scale') ) && $sell["scale"])
		{
			$str.= ";原重量:{$sell[scale]} 被修改为：".$this->input->post('scale');
		}
		$intransit = 0;
		if($postdata["custom"]==1){
			//均码信息
			$postdata["model"] = $this->input->post('model');
			if($sell["model"] != $this->input->post('model'))
			{
				if( $this->input->post('model')==1) $person1 ="欧美";
			    if( $this->input->post('model')==2) $person1 ="亚洲";
				$str.= ";原版型:{$sell[model]} 被修改为：".$person1;
			}
			$postdata["gender1"] = $this->input->post('gender1');
			if($sell["gender1"] != $this->input->post('gender1'))
			{
				if( $this->input->post('gender1')==1) $gender1 ="男";
			    if( $this->input->post('gender1')==2) $gender1 ="女";
				$str.= ";原性别:{$sell[gender1]} 被修改为：".$gender1;
			}
			$postdata["size"] = $this->input->post('size');
			if($sell["size"] != $this->input->post('size'))
			{
				$str.= ";原尺寸:{$sell[size]} 被修改为：". $this->input->post('size');
			}

			//如果是均码，判断是否有五位关联并且是否有在途。如果有在途直接进入审核列表
			$linksku = $this->input->post('linksku');
			$intransit = $this->input->post('intransit');
			$urgentordermemo = $this->input->post('urgentordermemo');
			if($linksku){
				$postdata["linksku"] = $linksku;
			}

		}

		if($postdata["custom"]==2 || $postdata["custom"]==3)	{
			$postdata["model"] = null;
			$postdata["gender1"] =null;
			$postdata["size"] =null;
			
			$postdata["gender"] = $this->input->post('gender');
			if($sell["gender"] != $this->input->post('gender'))
			{
				if( $this->input->post('gender')==1) $gender ="男";
			    if( $this->input->post('gender')==2) $gender ="女";
				$str.= ";原性别:{$sell[gender]} 被修改为：".$gender;
			}

			
			if($sell["leixing"] != $this->input->post('leixing'))
			{
				if( $this->input->post('leixing')=='lingmi') $gender ="cm";
			    if( $this->input->post('leixing')=='yingcun') $gender ="inch";
				$str.= ";原类型:{$sell[leixing]} 被修改为：".$gender;
			}

			$postdata["leixing"] = $this->input->post('leixing');
		
			if($postdata["leixing"]=="lingmi")
			{
				
				$postdata["height"] = $this->input->post('height');
				if($sell["height"] != $this->input->post('height'))
				{
					$str.= ";原身高:{$sell[height]} 被修改为：".$this->input->post('height');
				}
				$postdata["weight"] = $this->input->post('weight');
				if($sell["weight"] != $this->input->post('weight'))
				{
					$str.= ";原体重:{$sell[weight]} 被修改为：".$this->input->post('weight');
				}
				$postdata["bust"] = $this->input->post('bust');
				if($sell["bust"] != $this->input->post('bust'))
				{
					$str.= ";原胸围:{$sell[bust]} 被修改为：".$this->input->post('bust');
				}
				$postdata["waistline"] = $this->input->post('waistline');
				if($sell["waistline"] != $this->input->post('waistline'))
				{
					$str.= ";原腰围:{$sell[waistline]} 被修改为：".$this->input->post('waistline');
				}
				$postdata["hipline"] = $this->input->post('hipline');
				if($sell["hipline"] != $this->input->post('hipline'))
				{
					$str.= ";原臀围:{$sell[hipline]} 被修改为：".$this->input->post('hipline');
				}
				$postdata["shoulder"] = $this->input->post('shoulder');
				if($sell["shoulder"] != $this->input->post('shoulder'))
				{
					$str.= ";原肩宽:{$sell[shoulder]} 被修改为：".$this->input->post('shoulder');
				}
				$postdata["outside"] = $this->input->post('outside');
				if($sell["outside"] != $this->input->post('outside'))
				{
					$str.= ";原臂长:{$sell[outside]} 被修改为：".$this->input->post('outside');
				}
				$postdata["inseam"] = $this->input->post('inseam');
				if($sell["inseam"] != $this->input->post('inseam'))
				{
					$str.= ";原内接缝:{$sell[outside]} 被修改为：".$this->input->post('inseam');
				}
			}else{
				$postdata["height"] = $this->input->post('heightyingchun')*2.54;
				if($sell["height"] != $this->input->post('heightyingchun'))
				{
					$str.= ";原身高:{$sell[height]} 被修改为：".$this->input->post('heightyingchun');
				}
				$postdata["weight"] = $this->input->post('weightyingchun')*0.4532;
				if($sell["weight"] != $this->input->post('weightyingchun'))
				{
					$str.= ";原体重:{$sell[weight]} 被修改为：".$this->input->post('weightyingchun');
				}
				$postdata["bust"] = $this->input->post('bustyingchun')*2.54;
				if($sell["bust"] != $this->input->post('bustyingchun'))
				{
					$str.= ";原胸围:{$sell[bust]} 被修改为：".$this->input->post('bustyingchun');
				}
				$postdata["waistline"] = $this->input->post('waistlineyingchun')*2.54;
				if($sell["waistline"] != $this->input->post('waistlineyingchun'))
				{
					$str.= ";原腰围:{$sell[waistline]} 被修改为：".$this->input->post('waistlineyingchun');
				}
				$postdata["hipline"] = $this->input->post('hiplineyingchun')*2.54;
				if($sell["hipline"] != $this->input->post('hiplineyingchun'))
				{
					$str.= ";原臀围:{$sell[hipline]} 被修改为：".$this->input->post('hiplineyingchun');
				}
				$postdata["shoulder"] = $this->input->post('shoulderyingchun')*2.54;
				if($sell["shoulder"] != $this->input->post('shoulderyingchun'))
				{
					$str.= ";原肩宽:{$sell[shoulder]} 被修改为：".$this->input->post('shoulderyingchun');
				}
				$postdata["outside"] = $this->input->post('outsideyingchun')*2.54;
				if($sell["outside"] != $this->input->post('outsideyingchun'))
				{
					$str.= ";原臂长:{$sell[outside]} 被修改为：".$this->input->post('outsideyingchun');
				}
				$postdata["inseam"] = $this->input->post('inseamyingchun')*2.54;
				if($sell["inseam"] != $this->input->post('inseamyingchun'))
				{
					$str.= ";原内接缝：{$sell[outside]} 被修改为：".$this->input->post('inseamyingchun');
				}
				
			}
			$postdata["leixing"] ="lingmi";	//强制使用lingmi

			
		}

		  $this->db->trans_begin();
			if($this->input->post('descr')){
				if($order["descr"] != $this->input->post('descr'))
				{
					$str.= ";原备注：{$order[descr]} 被修改为：".$this->input->post('descr');
				}
				$this->db->update('db_factory_order',array("descr"=>trim($this->input->post('descr'))),"id='".$orderId."'");
			}else{
				if($order["descr"])
				{
					$str.= ";原备注：{$order[descr]} 被修改为：空";
				}
				$this->db->update('db_factory_order',array("descr"=>''),"id='".$orderId."'");
			}
			if($this->input->post('deliveryTime')){
				if($order["deliveryTime"] != $this->input->post('deliveryTime'))
				{
					$str.= "原交货日期：{$order[deliveryTime]} 被修改为：".$this->input->post('deliveryTime');
				}
				$this->db->update('db_factory_order',array("deliveryTime"=>trim($this->input->post('deliveryTime'))),"id='".$orderId."'");
			}else{
				if($order["deliveryTime"]){
					$str.= "原交货日期：{$order[deliveryTime]} 被修改为：空";
				}
				$this->db->update('db_factory_order',array("deliveryTime"=>''),"id='".$orderId."'");
			}

		

		  $this->db->update("db_factory_sell",$postdata," orderId='".$orderId."'");
		  if($str){
			 $this->db->insert("db_factory_orderlog",array("orderId"=>$orderId,"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>$str,"spcodeid"=>1));
		  }
	
		  
		if($postdata["custom"])
		{
			if($intransit && $postdata["custom"]==1 && $urgentordermemo)
			{
				//说明有在途，并且是均码，填写了理由,进入加急列表
				$this->db->update('db_factory_order',array("orderurgent"=>'17',"updateflag"=>0,"orderurgenttip"=>'',"nature"=>$urgentordermemo),"id='".$orderId."'");//优先发货订单
				$text = "有在途派单申请理由->".$urgentordermemo;
				$this->db->insert("db_factory_orderlog",array("orderId"=>$orderId,"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>$text,"spcodeid"=>1));
			}else{
				$this->db->update("db_factory_order",array("updateflag"=>9)," id='".$orderId."'");//标识该订单被派单了。工厂显示新订单！销售显示派单
			}

			 
		}

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
		
		return $orderId;
	}
	function saveScanRules()
	{
		$postdata= "";
		$postdata["name"]    = trim($this->input->post('name'));
		$postdata["country"] = trim($this->input->post('country'));
		$postdata["countryflag"] = trim($this->input->post('countryflag'));
		$postdata["shopname"] = trim($this->input->post('shopname'));
		$postdata["shopflag"] = trim($this->input->post('shopflag'));

		$postdata["weight1"] = trim($this->input->post('weight1'));
		$postdata["weight2"] = trim($this->input->post('weight2'));
		$postdata["freight1"] = trim($this->input->post('freight1'));
		$postdata["freight2"] = trim($this->input->post('freight2'));
		$postdata["days"] = trim($this->input->post('days')); //延迟天数

		$postdata["logisticsID"]  =trim($this->input->post('logisticsID'));
		$rsdb = $this->fun->getdatabasesdetail("db_order_express"," AND id=".trim($this->input->post('logisticsID')));
		$postdata["logistics"] = $rsdb["name"];
		
		$postdata["ordermoney1"] = trim($this->input->post('ordermoney1'));
		$postdata["ordermoney2"] = trim($this->input->post('ordermoney2'));

		$postdata["priority"] = trim($this->input->post('priority'));
		$postdata["opertime"] = date("Y-m-d H:i:s");
		$postdata["oper"] = $_COOKIE["username"];
		$this->db->trans_begin();

		if($this->input->post("id"))
		{
			$this->db->update("db_factory_scanrules",$postdata,"id=".$this->input->post("id"));
			$intid =intval($this->input->post("id"));
		}else{
			$this->db->insert("db_factory_scanrules",$postdata);
			$intid = $this->db->insert_id();
		}


		$sql = "";
		if($postdata["country"])	//国家Sql
		{
			$country = explode(";",$postdata["country"]);
			$country = implode("','",$country );
			if($this->input->post("countryflag")==1)
				$sql.= " AND country_cn not in ('".$country."')";
			else
				$sql.= " AND country_cn in ('".$country."')";
		}
		if($postdata["shopname"])	//店铺SQL
		{
			$shopname = explode(";",$postdata["shopname"]);
			$shopname = implode("','",$shopname );
			if($this->input->post("shopflag")==1)
				$sql.= " AND shopname not in ('".$shopname."')";
			else
				$sql.= " AND shopname in ('".$shopname."')";
		}
		if($postdata["freight1"])	//运费SQL
		{
			$sql.= " AND shipping_fee >= $postdata[freight1] ";
		}
		if($postdata["freight2"]){
			$sql.=" AND shipping_fee <= $postdata[freight2] ";
		}

		if($postdata["ordermoney1"]){
			$sql.=" AND goods_amount >= $postdata[ordermoney1] ";
		}
		if($postdata["ordermoney2"]){
			$sql.=" AND goods_amount <= $postdata[ordermoney2] ";
		}

		/**
		if($postdata["weight1"])	//订单重量 不取该值，获取工厂订单的实际重量值
		{
			$sql.= " AND orderweight >= {$postdata['weight1']}  ";
		}
		if($postdata["weight2"]){
			$sql.=" AND orderweight <= {$postdata['weight2']} ";
		}**/
		if($sql)
		{
			$this->db->update("db_factory_scanrules",array("sqlfilter"=>$sql),"id=".$intid);
		}
		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
			return false;
		}
		else
		{
			$this->db->trans_commit();
		}

		return true;
	}

		
	function getfactoryorder($orderId)
	{
		if($orderId)
		{
			$orderInfo = $this->db->get_where('db_factory_order',"orderId='".$orderId."'")->result_array();
			$orderInfo[0]["orderTime"] = date("Y-m-d",strtotime($orderInfo[0]["orderTime"]));
			$goodslist = $this->fun->getdatabasesdetail("db_factory_sell"," AND orderId='".$orderInfo[0]["id"]."'");
			$goods_images = $this->fun->getdatabasesdetail(" db_goods A LEFT JOIN db_goods_images C ON A.goods_id = C.goods_id"," AND A.goods_sku='".$goodslist["goods_sku"]."'");
			$shop =  $this->fun->getdatabasesdetail("d_shop"," AND name='".$orderInfo[0]["shopId"]."'");	//负责人
			$orderInfo[0]["responsible"] = $shop["updateoper"];
			$local_url = $goods_images["local_url"];
			if ($local_url) {
				 $goodslist["local_url"] = "/".$goods_images["local_url"];
			} else {
				 $goodslist["local_url"] = "/fuman/images/s-l500.jpg";
			}
			 $goodslist["standard"] = $goods_images["standard"];
			 $orderInfo[0]["sell"] = $goodslist; 

			return $orderInfo;
		}
		
	}
	
	function saveexress($orderdata,$Dhldeliver,$orderType)
	{
		$data = $this->db->get_where("db_order_list","order_sn in ('".$orderdata."')")->result_array();
		if(count($data)>0){
			foreach($data as $key=>$rs){
			     $insert_ids=array();
			     $insert_ids['order_id']=$rs['order_id'];
                 $insert_ids['order_sn']=$rs['order_sn'];
		
				$rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE orderID='".trim($rs["order_sn"])."' AND orderType ='".$orderType."'");
				if($rsdb)
				{
					$thi1orderid = $rsdb["id"];
				}else{
					$thi1orderid = 0;
				}

				if( !$rs["tel"] &&  !$rs["mobile"])
				{
					$rs["tel"] = '0000000000';
				}
				
				$statustext  = '已支付';
				$postdata["orderType"] = $orderType;
				$postdata["orderID"] = trim($rs["order_sn"]);
				$postdata["statusst"]=$statustext;
				$postdata["customerid"] = $rs["consignee"];
				$postdata["customertype"]= $rs["shopname"];
				$postdata["customertel1"]= $rs["tel"];
				$postdata["customertel2"]= $rs["mobile"];
				//获取国家标识strtoupper
				if($rs["country_code"] =='')
				{
					$rscountry = $this->fun->getdatabasesdetail("d_country"," AND countrynamecn='".strtoupper(trim($rs["country"]))."'");
					if($rscountry)
					{
						$customerqq = $rscountry["countryid"];
					}
				}else{
					$customerqq = $rs["country_code"];
				}


				$strprovince = strlen($rs["province"]);
				if($strprovince>3 ||  $rs["province"] =='')
				{
					//自动抓取省code
					$resprovince = $this->fun->getdatabasesdetail("d_country_state"," AND name='".trim($rs["province"])."'");
					$province = $resprovince['code'];
				}else{
					$province =$rs["province"];
				}

				$postdata["customerqq"]= $customerqq;	//国家标识
				$postdata["customercountry"]= $rs["country"];//国家
				$postdata["customerprovince"]= $province;
				$postdata["customercity"]= $rs["city"];
				$postdata["customeraddress"]= $rs["address"].$rs["address2"];
				$postdata["customerzipcode"]= $rs["zipcode"];
				$postdata["moneytype"]= $rs["moneytype"];
				$postdata["wuyconfig"]= $newwuconfig?$newwuconfig:null;
				$postdata["content1"]= NULL;
				$postdata["intime"]= date("Y-m-d H:i:s");
				$postdata["createUser"]=$_COOKIE["username"];
				if($deliver){
					$postdata['deliver'] = $Dhldeliver;
				}
				if( $thi1orderid)
				{
					$postdata["isexe"]= 0;
					$postdata["exememo"]='重复提交订单';
					$this->db->update('db_mabangorder', $postdata, 'id=' . $thi1orderid);
					$insert_ids['mabang_id']=$thi1orderid;
				   
				}else{
					 $res = $this->db->query($this->db->insert_string('db_mabangorder', $postdata));
					 $insert_ids['mabang_id']=$this->db->insert_id();
				}
                $insert_data[]=$insert_ids;
			}
		}

		return $insert_data;
	}

    public function checkExpPriec($objExcel,$express_type){
        $sheet = $objExcel->getSheet(0);    
        $rows = $sheet->getHighestRow(); //总行数
        $cols = "L";//$sheet->getHighestColumn(); //总列数 英文大写字母
        $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ');
        $cols_length = array_search($cols, $arrCellName); //获取数组下标最大数
        $arr_deliver = array();
        $str_conn = "";

        $date_colnum=0;
        $goodsName_colnum=3;
        $orderNumber_colnum=1;
        $sku_colnum=2;
        $style_colnum=4;
        $sex_colnum=5;
        $size_colnum=6;
        $numbers_colnum=7;
        $price_colnum=8;
        $data_type=1;
        $data_start_row=2;

        //行
        for($row=$data_start_row;$row<=$rows;$row++){
            $deliverNumber = $sheet->getCell($arrCellName[$orderNumber_colnum].$row)->getValue();
            if(empty($deliverNumber) || $deliverNumber=='订单编号(必填)'){//单个定制的列字段
                $date_colnum=1;
                $orderNumber_colnum=0;
                $sku_colnum=3;
                $style_colnum=11;
                $sex_colnum=11;
                $goodsName_colnum=11;
                $size_colnum=2;
                $numbers_colnum=4;
                $price_colnum=5;
                $data_type=2;
                continue;
                
            }
            //列
            for($column=0;$column<= $cols_length;$column++){
                $cellValue = $arrCellName[$column].$row; //A2
                $col_val = $sheet->getCell($cellValue)->getValue();
                $col_val_len = strlen($col_val);
                $arr_deliver[$row]['data_type']=$data_type;
                $arr_deliver[$row]['id']=$row;
                //订单号
                if($column==$orderNumber_colnum){
                    $arr_deliver[$row]['order_number'] = trim($col_val);
                    $str_conn.="'".$col_val."'".",";
                }
                //日期
                if($column==$date_colnum){
                    if(is_numeric($col_val)){
                       // $formatcode=$sheet->getCell($cellValue)->getFormatCode();  
                        $col_val=PHPExcel_Style_NumberFormat::toFormattedString($col_val,'Y/m/d');
                    }
                    $arr_deliver[$row]['made_date'] = $col_val;
                }
                //名称
                if($column==$goodsName_colnum){
                    $arr_deliver[$row]['goods_name'] = $col_val;
                }
                //sku
                if($column==$sku_colnum){
                    $arr_deliver[$row]['sku'] = $col_val;
                }
                //版形
                if($column==$style_colnum){
                    $arr_deliver[$row]['style'] = $col_val;
                }
                //性别
                if($column==$sex_colnum){
                    $arr_deliver[$row]['sex'] = $col_val;
                }
                //尺寸
                if($column==$size_colnum){
                    $arr_deliver[$row]['size'] = $col_val;
                }
                //数量
                if($column==$numbers_colnum){
                    $arr_deliver[$row]['numbers'] = $col_val;
                }
                //关联价出厂价
                if($column==$price_colnum){
                    $arr_deliver[$row]['costprice'] = $col_val;
                }
            }
        }
        $arr_tmp = array();
        $str_conn = trim($str_conn,",");
        return $arr_deliver;  
    }
	
}

/* End of file Factory_m.php */